#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This application is released under the GNU General Public License 
# v3 (or, at your option, any later version). You can find the full 
# text of the license under http://www.gnu.org/licenses/gpl.txt. 
# By using, editing and/or distributing this software you agree to 
# the terms and conditions of this license. 
# Thank you for using free software!


import threading
import ALSong
import lrcdb
import minilyrics

class ThreadDownloader(threading.Thread):
	def __init__(self, task, finishCallback):
		threading.Thread.__init__(self)
		self.task           = task
		self.finishCallback = finishCallback
		
	def setParams(self, *params):
		self.params = params
		
	def run(self):
		self.task(*self.params)
		self.finishCallback()
		
LYRICS_SOURCES = ['alsong', 'minilyrics', 'lrcdb']
	
class LyricsEngine:
	
	isRunning   = False
	searchQueue = None  # really simple queue
	
	def __init__(self, resultCallback, finishCallback):
		self.resultCallback = resultCallback
		self.finishCallback = finishCallback
		self.lyricsSources = []
		
		#alsongEngine = ALSong.ALSongEngine(self.resultCallback)
		#lrcdbEngine = lrcdb.LrcdbEngine(self.resultCallback)
		#minilyricsEngine = minilyrics.MiniLyricsEngine(self.resultCallback)
		alsongEngine = ALSong.ALSongEngine(self.lyrics)
		lrcdbEngine = lrcdb.LrcdbEngine(self.lyrics)
		minilyricsEngine = minilyrics.MiniLyricsEngine(self.lyrics)
		
		self.lyricsEngines = {'alsong':alsongEngine, 'lrcdb':lrcdbEngine, 'minilyrics':minilyricsEngine}
		
	def lyrics(self, lyrics):
		# filter lyrics here if needed
		#print "filer lyrics"
		try:
			import chardet
			encoding = chardet.detect(lyrics)
			print encoding
			#print lyrics.decode(encoding['encoding'], 'ignore')
			self.resultCallback(lyrics.decode(encoding['encoding'], 'ignore'))
		except:
			self.resultCallback(unicode(lyrics, 'utf-8'))
		
	def setLyricsSources(self, sources):
		self.lyricsSources = sources

	def search(self, songInfo):
		print "SEARCH FOR %s" % songInfo['title']
		if self.isRunning == True:
			#print "I SHOULD SEARCHING, BUT STILL RUNNING"
			self.searchQueue = songInfo
			return
		
		self.isRunning = True
		self.finished = 0
		for source in self.lyricsSources:
			print "start %s" % source
			engine = self.lyricsEngines[source]
			downloader = ThreadDownloader(engine.find, self.onDownloaderFinish)
			downloader.setParams(songInfo)
			downloader.start()
			
	def stop(self):
		for source in self.lyricsSources:
			engine = self.lyricsEngines[source]
			engine.stop()
		
	def onDownloaderFinish(self):
		self.finished += 1
		#print "finished downloaders: %d" % self.finished
		if self.finished == len(self.lyricsSources):
			if self.searchQueue == None:
				#print "BUT ANOTHER SEARCHING FALLOW"
				self.finishCallback()
			self.isRunning = False
			if self.searchQueue != None:
				#print "&&&&&&&& SEARCH FROM QUEUE &&&&&&&&&&&"
				self.search(self.searchQueue)
				self.searchQueue = None
